var salt = sessionStorage.getItem('usersalt');
var box = /\s/g;
$('#submitsev').on('click', function() {
	addrisk();
});
var arr = new Array();
var arr2 = new Array();
var danweim = '';

function GetQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if(r != null) return decodeURI(r[2]);
	return null;
}
/*-------------新增-------------*/
function addrisk() {

	var title = $.trim($('#title').val()); //操作项目
	var controlled = $.trim($('#controlled').val()); //受控号
	var type = $.trim($('#type').val()); //操作卡类别
	var releaseTime = $.trim($('#releaseTime').val()); //发布时间
	var reviseTime = $.trim($('#reviseTime').val()); //修订时间
	var postUrl;
	if($('#id').val() == '') {
		postUrl = url + 'operateCard/add'
	} else {
		postUrl = url + 'operateCard/edit'
	}
	if(title != '' && controlled != '' && type != '' && releaseTime != '' && reviseTime != '' && arr.toString() != '' && getval().toString() != '') {
		$.ajax({
			url: postUrl,
			dataType: 'json',
			async: false,
			type: "POST",
			data: {
				id: $('#id').val(),
				Token: salt,
				attId: arr.toString(),
				title: title,
				controlled: controlled,
				type: type,
				releaseTime: releaseTime,
				reviseTime: reviseTime,
				cardType: 0,
				staffName: $.trim($('#staffName').val()),
				trainTime: $.trim($('#trainTime').val()),
				trainResult: $.trim($('#trainResult').val()),
				post: getval().toString()

			},
			success: function(data) {
				console.log(data);
				if(data.code == 0) {
					layer.confirm('操作卡提交成功！', {
						btn: ['确定'] //按钮
					}, function() {
						location.href = "../list/operateCard.html";
					}, function() {

					});
				} else {
					layer.msg(data.msg);
				}

			},
			error: function(error) {
				console.log("获取失败");
			}
		});
	} else {
		layer.msg('请填写完整');
	}

}
$('#updatapic').on('click', function() {
	$("#selfile").click();
});

/*删除事件*/
function delpic(self, num, inde) {
	layer.confirm('你确定要删除吗？', {
		btn: ['确定', '取消'] //按钮
	}, function() {
		$('#' + self).remove();
		console.log(arr);
		for(var i = 0; i < arr.length; i++) {
			if(arr[i] == inde) {
				arr.splice(i, 1);
			}
		}

		console.log(arr);
		layer.msg('删除成功');
	}, function() {

	});
}

function lookbigpic(self) {

	console.log(self);
	//	$.getJSON('test/photos.json?v=' + new Date, function(json) {
	var json = {
		"status": 1,
		"msg": "",
		"title": "",
		"id": 8,
		"start": 0,
		"data": [{
			"alt": "",
			"pid": 109,
			"src": url + "attachment/seekFile/" + self,
			"thumb": ""
		}]
	}
	layer.photos({
		photos: json,
		anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机
	});

}

$('#resclas').click(function() {
	$('#resclass').show();
});

var company;

getallent();

function getallent() {

	$.ajax({
		url: url + 'post/getAllEnt',
		dataType: 'json',
		async: false,
		type: "POST",
		data: {

		},
		success: function(data) {
			console.log(data);
			$('#resclass').empty();
			if(data.code == 0) {
				var list = data.data;
				company = list;

			}

		},
		error: function(error) {
			console.log("获取失败");
		}
	});

}

var setting = {
	check: {
		enable: true
	},
	data: {
		simpleData: {
			enable: true
		}
	},
	callback: {
		onCheck: zTreeOnCheck
	}
};

var zNodes = company;

$.fn.zTree.init($("#resclass"), setting, zNodes);

$('#getval').click(function() {
	console.log(1)
	getval();
})

function zTreeOnCheck(event, treeId, treeNode) {
	//	var checked = treeNode.checked;
	//	console.log((treeNode ? treeNode.name : "root"));
	//	danweim = treeNode ? treeNode.name : "root"
	//	$('#resclas').val(danweim)
	//	$('#resclass').hide();

	var treeObj = $.fn.zTree.getZTreeObj("resclass");
	var nodes = treeObj.getCheckedNodes(true),
		n = "";
	for(var i = 0; i < nodes.length; i++) {
		n += nodes[i].name + ",";
		$('#resclas').val(n)

	}

};

function getval() {
	arr2 = [];
	danweim = '';
	var treeObj = $.fn.zTree.getZTreeObj("resclass");
	var nodes = treeObj.getCheckedNodes(true),

		v = "";
	for(var i = 0; i < nodes.length; i++) {
		v += nodes[i].name + ",";

		arr2.push(nodes[i].id); //获取选中节点的值
	}
	return arr2;
}

layui.use(['form', 'layer', 'laydate', 'table', 'laytpl'], function() {
	var form = layui.form,
		layer = parent.layer === undefined ? layui.layer : top.layer,
		$ = layui.jquery,
		laydate = layui.laydate,
		laytpl = layui.laytpl,
		table = layui.table;
	if(!sessionStorage.getItem('username')) {
		layer.msg('请先登录');
		setTimeout("top.location.href='../../../index.html'", 1000);

	}
	if(GetQueryString("id") != '') {
		$.post(url + 'operateCard/getInfo', {
				Token: salt,
				id: GetQueryString("id")
			},
			function(data) {
				$('#divtitle').html('编辑操作卡')
				$('#id').val(data.data.id);
				$('#title').val(data.data.title); //操作项目
				$('#controlled').val(data.data.controlled); //受控号
				$('#releaseTime').val(data.data.releaseTime); //发布时间
				$('#reviseTime').val(data.data.reviseTime); //修订时间
				$('#staffName').html(data.data.staffName);
				$('#trainTime').val(data.data.trainTime);
				$('#trainResult').html(data.data.trainResult);
				$('#type').find("option:contains('" + data.data.type + "')").attr("selected", true);
				$('#type').find("option[value='" + data.data.type + "']").attr("selected", true);
				arr.push(data.data.attId);
				var flg = 1;
				var img = $('<div style="display:inline-block;position:relative;margin-right:45px;" id="picupfile' + flg + '"  ><div onclick="delfile(\'picupfile' + flg + '\',\'' + flg + '\',\'' + data.data.attId + '\')" style="position:absolute;top:-2px;right:-21px;color:red;width:16px;height:16px"><i class="layui-icon" style="position:relative;top:-2px;right:0px;">&#x1006;</i></div><a style="color: blue;text-decoration: underline;" href="' + url + 'attachment/seekFile/' + data.data.attId + '" >' + data.data.attName + '</a></div>');
				$('#picapp').append(img);
				var treeObj = $.fn.zTree.getZTreeObj("resclass");
				for(var i = 0; i < data.data.post.split(",").length; i++) {
					console.log(data.data.post.split(",")[i]);
					var node = treeObj.getNodeByParam("id", data.data.post.split(",")[i], null);
					treeObj.checkNode(node);
					$('#resclas').val(data.data.postName);
				}

				form.render();
			});
	}
	//	$('#picapp').on('click', function() {
	//		layer.photos({
	//			photos: '#picupdata1',
	//			anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
	//		});
	//	});

	laydate.render({
		elem: '#releaseTime',
		trigger: 'click'
	});

	laydate.render({
		elem: '#reviseTime',
		trigger: 'click'
	});
	laydate.render({
		elem: '#trainTime',
		format: 'yyyy-MM-dd HH:mm',
		trigger: 'click',
		type: 'datetime'
	});

	/*上传图片 */
	var flg = 0;

	layui.use('upload', function() {
		var $ = layui.jquery,
			upload = layui.upload;

		upload.render({
			elem: '#test2',
			url: url + 'attachment/upload',
			multiple: true,
			accept: 'file',
			exts: 'pdf',
			before: function(obj) {},
			done: function(res) {
				//上传完毕
				console.log(res);
				if(res.code == 0) {
					flg++;
					console.log(res);
					arr.push(res.data.id);
					console.log(arr);

					var img = $('<div style="display:inline-block;position:relative;margin-right:45px;" id="picupfile' + flg + '"  ><div onclick="delfile(\'picupfile' + flg + '\',\'' + flg + '\',\'' + res.data.id + '\')" style="position:absolute;top:-2px;right:-21px;color:red;width:16px;height:16px"><i class="layui-icon" style="position:relative;top:-2px;right:0px;">&#x1006;</i></div><a style="color: blue;text-decoration: underline;" href="' + url + 'attachment/seekFile/' + res.data.id + '" >' + res.data.originaName + '</a></div>');
					$('#picapp').append(img);

				}
			}
		});

	});

});